import { BrowserWindow, shell } from "electron";
import { join } from "path";
import { is } from "@electron-toolkit/utils";
import { winConfig } from "./configs";

const config = winConfig.main

export default class MainWindow {
    private static _instance: BrowserWindow;
    public static get instance(): BrowserWindow {
        if (!this._instance) {
            this.createWindow();
        }
        return this._instance;
    }
    public static createWindow(): BrowserWindow {
        // Create the browser window.
        this._instance = new BrowserWindow(config)

        this._instance.on('ready-to-show', () => {
            this._instance.show()
        })

        this._instance.webContents.setWindowOpenHandler((details) => {
            shell.openExternal(details.url)
            return { action: 'deny' }
        })

        // HMR for renderer base on electron-vite cli.
        // Load the remote URL for development or the local html file for production.
        if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
            this._instance.loadURL(process.env['ELECTRON_RENDERER_URL'] +  config.url)
        } else {
            this._instance.loadFile(join(__dirname, '../renderer', config.url))
        }
  
        const winID = this._instance.webContents.id
        // map存储窗口ID
        global.winObj.winMap.set('main', winID)
        // 全局存储窗口对象
        global['winstates-' + winID] = this._instance
        return this._instance;
    }
}